<template>
  <div>
    <h1>购物车</h1>
    <!-- 购物车商品列表 -->
    <div class="cart-items">
      <div class="cart-item" v-for="(item, index) in cartItems" :key="index">
        <div class="item-product">
          <img :src="item.product.cover" alt="商品图片" class="cart-item-img">
          <div class="product-info">
            <div class="cart-item-title">{{ item.product.title }}</div>
          </div>
        </div>
        <div class="item-price">¥{{ item.product.price / 100 }}</div>
        <div class="item-quantity">
          <div class="quantity-control">
            <button class="quantity-btn" @click="decreaseQuantity(index)">-</button>
            <input type="number" class="quantity-input" v-model.number="item.qty" min="1"
                   @change="updateSubtotal(index)">
            <button class="quantity-btn" @click="increaseQuantity(index)">+</button>
          </div>
        </div>
        <div class="item-subtotal">¥ {{ calculateItemTotal(item) }}</div>
        <div class="item-action">
          <span class="remove-btn" @click="removeCartItem(index)">删除</span>
          <a href="javascript:void(0)" style="margin:auto 10px" @click="modifyQuantity(index)"  v-if="item.qty > 0">修改</a>
          <button type="button" class="btn btn-primary" @click="placeOrder" :disabled="item.qty < 1">下单</button>
        </div>
      </div>
    </div>
    <!-- 分页组件 -->
    <Pagination v-if="cartItems.length>0" :current-page="currentPage" :total-pages="totalPages" @page-changed="handlePageChange"/>
    <div class="cart-footer" v-if="cartItems.length>0">
      <div class="cart-actions" >
        <button class="btn btn-danger" @click="clearCart">清空购物车</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import Pagination from "@views/common/Pagination.vue";
import apis from "@/config/api-config.js";
import getResponse from "@/assets/js/http-client.js";
import {ElMessage} from "element-plus";

const currentPage = ref(1);
const totalPages = ref(1);
const pageSize = ref(3);
// 购物车数据
const cartItems = ref([])
// 计算单个商品总价
const calculateItemTotal = (item) => {
  return (item.product.price / 100) * item.qty
}

// 增加数量
const increaseQuantity = (index) => {
  cartItems.value[index].qty++
}

// 减少数量
const decreaseQuantity = (index) => {
  if (cartItems.value[index].qty > 1) {
    cartItems.value[index].qty--
  }
}
const modifyQuantity =async (index) => {
  if (cartItems.value[index].qty < 1) {
    ElMessage.error('购买数量不能小于1');
    return
  }
  let url = apis.cart.modify.url;
  let type = apis.cart.modify.type;
  let params = {
    id: cartItems.value[index].id,
    qty: cartItems.value[index].qty
  }
  let result = await getResponse(url, type, params);
  if (200 !== result.code) {
    ElMessage.error(result.message);
    return
  }
  ElMessage.success('修改数量成功');
}
// 分页组件 - 页码改变时触发
const handlePageChange = async (page) => {
  currentPage.value = page;
  await loadCartItems();
}
const loadCartItems = async () => {
  let url = apis.cart.list.url;
  let type = apis.cart.list.type;
  let params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value
  }
  let result = await getResponse(url, type, params);
  if (200 !== result.code) {
    ElMessage.error(result.message);
    return
  }
  let list = result.data.records;
  if (list == null || undefined === list || 0 === list.length) {
    console.info('购物车为空');
    list = [];
  }
  cartItems.value = list;
  totalPages.value = result.data.pages;
}
// 更新小计
const updateSubtotal = (index) => {
  cartItems.value[index].subtotal =
      cartItems.value[index].price * cartItems.value[index].quantity
}

// 删除商品
const removeCartItem = async (index) => {
  if (!confirm(`确定将【${cartItems.value[index].product.title}】从购物车中删除吗？`)) {
    return
  }
  let url = apis.cart.remove.url;
  let type = apis.cart.remove.type;
  let params = {
    cartId: cartItems.value[index].id
  }
  let result = await getResponse(url, type, params);
  if (200 !== result.code) {
    ElMessage.error(result.message);
    return
  }
  ElMessage.success('删除成功');
  currentPage.value = 1;
  await loadCartItems();
}

// 清空购物车
const clearCart = async () => {
  if (!confirm('确定要清空购物车吗？')) {
    return
  }
  let url = apis.cart.clear.url;
  let type = apis.cart.clear.type;
  let result = await getResponse(url, type);
  if (200 !== result.code) {
    ElMessage.error(result.message);
    return
  }
  ElMessage.success('清空成功');
  currentPage.value = 1;
  await loadCartItems();
}

// 下单
const placeOrder = () => {
  if (cartItems.value.length === 0) {
    alert('购物车为空，请先添加商品')
    return
  }
  alert('下单成功！')
  // 这里可以添加实际的下单逻辑
}
onMounted(async () => {
  await loadCartItems();
});
</script>

<style scoped>

/* 购物车商品项样式 */
.cart-items {
  display: flex;
  flex-direction: column;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.item-product {
  flex: 0 0 40%;
  display: flex;
  align-items: center;
}

.product-info {
  margin-left: 10px;
}

.item-price {
  flex: 0 0 10%;
  color: #e53935;
  font-weight: bold;
}

.item-quantity {
  flex: 0 0 10%;
}

.item-subtotal {
  flex: 0 0 10%;
  color: #e53935;
  font-weight: bold;
}

.item-action {
  flex: 0 0 30%;
}

.cart-item-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.cart-item-title {
  font-weight: 500;
  color: #333;
}


.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 30px;
  height: 30px;
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  cursor: pointer;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.quantity-input {
  width: 50px;
  height: 30px;
  text-align: center;
  border: 1px solid #ddd;
  margin: 0 5px;
}

.remove-btn {
  color: #6c757d;
  cursor: pointer;
  transition: color 0.3s;
}

.remove-btn:hover {
  color: #e53935;
}

/* 购物车底部结算区域 */
.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20px;
  border-top: 1px solid #eee;
}


.total-price span {
  color: #e53935;
}

.cart-actions {
  display: flex;
  gap: 15px;
}

.btn {
  padding: 0.8rem 1.5rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.3s;
}

.btn-danger {
  background-color: #e53935;
  color: #fff;
}

.btn-danger:hover {
  background-color: #c62828;
}

.btn-primary {
  background-color: #007BFF;
  color: #fff;
}

.btn-primary:hover {
  background-color: #0056b3;
}

.cart-item-img.hover-effect {
  transform: translateY(-3px);
  transition: transform 0.3s ease;
}

.quantity-control {
  display: flex;
  align-items: center;
  justify-content: center; /* 数量输入居中 */
}

.quantity-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.remove-btn {
  display: inline-flex;
  align-items: center;
  color: #666;
  cursor: pointer;
  transition: all 0.3s;
  padding: 5px 10px;
  border-radius: 4px;
}

.remove-btn:hover {
  color: #e53935;
  background-color: #f8f9fa;
}
</style>